// cloudfunctions/getHotPostsByProduct/index.js
const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    const { productId } = event;
    
    // 验证参数
    if (!productId) {
      return { success: false, message: '缺少productId参数' };
    }
    
    // 1. 查询关联该产品的所有帖子ID
    const relatedPostsResult = await db.collection('community_posts')
      .where({
        productRelations: _.elemMatch({ productId })
      })
      .field({
        _id: true,
        likeCount: true,
        commentCount: true,
        createTime: true,
        title: true,
        userAvatar: true,
        userName: true,
        images: true
      })
      .get();
    
    if (relatedPostsResult.data.length === 0) {
      return { 
        success: true, 
        data: [], 
        message: '没有找到关联该产品的帖子' 
      };
    }
    
    const relatedPosts = relatedPostsResult.data;
    
    // 2. 计算帖子热度并排序（热度公式：点赞数*0.5 + 评论数*0.3 + 浏览数*0.2）
    const hotPosts = relatedPosts.map(post => {
      // 计算热度值
      const heatScore = (post.likeCount * 0.5) + 
                        (post.commentCount * 0.3)
                        
      return {
        ...post,
        heatScore
      };
    })
    .sort((a, b) => b.heatScore - a.heatScore) // 按热度降序排列
    .slice(0, 3); // 取前3条
    
    return {
      success: true,
      data: hotPosts,
      message: `获取${productId}关联的热度最高的3个帖子成功`
    };
  } catch (error) {
    console.error('获取热度帖子失败', error);
    return {
      success: false,
      message: error.message || '服务器错误',
      error: error.message
    };
  }
};